package Student;//导入所有的 Swing 组件类，包括 JFrame, JPanel, JButton 等等
// Swing 是 Java 的一种图形用户界面工具包，用于创建窗口应用程序
import javax.swing.*;
//导入 DefaultTableModel 类，这是一个用于创建和管理 JTable 的表格模型
// 它允许动态更新表格中的数据，例如添加、删除行等
import javax.swing.table.DefaultTableModel;
//导入 AWT中的所有类，包括布局管理器和图形组件。这些用于 Swing 组件的外观和功能
import java.awt.*;
//导入 AWT 事件处理类，包括 ActionListener, MouseAdapter等等。
// 这些类用于处理用户的交互，如按钮点击、鼠标事件等
import java.awt.event.*;
//导入 Java 的集合框架类和其他工具类，这些类包括 ArrayList, HashMap, Map, Random 等等，
// 这些在处理数据集合和随机数生成时非常有用
import java.util.*;

public class Main{
    //管理学生信息
    private static StudentManager studentManager = new StudentManager();
    //管理班级信息
    private static ClassManager classManager = new ClassManager();
    //管理小组信息
    private static GroupManager groupManager = new GroupManager();
    //随机选择学生
    private static RandomSelector randomSelector = new RandomSelector();

    //使用 SwingUtilities.invokeLater 创建和显示 GUI
    //GUI是指图形用户界面，它通过图形方式显示和操作的用户界面
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGUI());
    }

    //创建窗口和面板
    private static void createAndShowGUI() {
        JFrame frame = new JFrame("学生管理系统");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(800, 600);

        //用 JTabbedPane 来实现多个选项卡（如班级管理、小组管理等）
        JTabbedPane tabbedPane = new JTabbedPane();

        // 创建各个面板
        tabbedPane.addTab("班级管理", createClassPanel());
        tabbedPane.addTab("小组管理", createGroupPanel());
        tabbedPane.addTab("学生管理", createStudentPanel());
        tabbedPane.addTab("随机点名", createRandomPanel());
        tabbedPane.addTab("考勤管理", createAttendancePanel());
        tabbedPane.addTab("答题记录", createAnswerRecordPanel());


        frame.add(tabbedPane);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    //班级管理面板
    private static JPanel createClassPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        //使用 DefaultListModel 和 JList 显示班级列表
        DefaultListModel<String> listModel = new DefaultListModel<>();
        JList<String> classList = new JList<>(listModel);
        //添加按钮用于新增班级，用户输入班级名称后被添加到 classManager 中
        JButton addButton = new JButton("新增班级");

        addButton.addActionListener(e -> {
            String className = JOptionPane.showInputDialog("请输入班级名称：");
            if (className != null && !className.trim().isEmpty()) {
                classManager.addClass(className);
            }
        });

        panel.add(new JScrollPane(classList), BorderLayout.CENTER);
        panel.add(addButton, BorderLayout.SOUTH);
        return panel;
    }

    //小组管理面板
    private static JPanel createGroupPanel() {
        JPanel panel = new JPanel(new BorderLayout());

        // 创建表格来显示小组和分数
        String[] columnNames = {"小组名称", "分数"};
        DefaultTableModel tableModel = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false; // 使表格不可编辑
            }
        };
        JTable groupTable = new JTable(tableModel);

        // 创建按钮面板
        JPanel buttonPanel = new JPanel();
        JButton addButton = new JButton("新增小组");
        JButton scoreButton = new JButton("评分");

        // 更新表格的方法
        Runnable updateTable = () -> {
            tableModel.setRowCount(0);
            Map<String, Double> scores = groupManager.getAllGroupScores();
            for (String group : groupManager.getAllGroups()) {
                tableModel.addRow(new Object[]{group, scores.get(group)});
            }
        };

        // 添加小组的动作
        addButton.addActionListener(e -> {
            String groupName = JOptionPane.showInputDialog("请输入小组名称：");
            if (groupName != null && !groupName.trim().isEmpty()) {
                groupManager.addGroup(groupName);
                updateTable.run();
            }
        });

        // 添加表格的双击事件监听器
        groupTable.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 2) { // 双击事件
                    int selectedRow = groupTable.getSelectedRow();
                    if (selectedRow != -1) {
                        String groupName = (String) tableModel.getValueAt(selectedRow, 0);
                        promptForScore(groupName, panel, updateTable);
                    }
                }
            }
        });

        // 评分按钮的动作
        scoreButton.addActionListener(e -> {
            int selectedRow = groupTable.getSelectedRow();
            if (selectedRow == -1) {
                JOptionPane.showMessageDialog(panel, "请先选择一个小组！");
                return;
            }
            String groupName = (String) tableModel.getValueAt(selectedRow, 0);
            promptForScore(groupName, panel, updateTable);
        });

        // 设置表格的选择模式和其他属性
        groupTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        groupTable.setRowHeight(25); // 设置行高
        groupTable.getTableHeader().setReorderingAllowed(false); // 禁止列重排序

        // 添加按钮到按钮面板
        buttonPanel.add(addButton);
        buttonPanel.add(scoreButton);

        // 添加组件到主面板
        panel.add(new JScrollPane(groupTable), BorderLayout.CENTER);
        panel.add(buttonPanel, BorderLayout.SOUTH);

        // 初始化表格数据
        updateTable.run();

        return panel;
    }

    // 提取评分对话框为单独的方法
    private static void promptForScore(String groupName, JPanel panel, Runnable updateTable) {
        String scoreStr = JOptionPane.showInputDialog(
                panel,
                "请输入" + groupName + "的分数（0-100）：",
                "小组评分",
                JOptionPane.QUESTION_MESSAGE
        );

        try {
            if (scoreStr != null && !scoreStr.trim().isEmpty()) {
                double score = Double.parseDouble(scoreStr);
                if (score >= 0 && score <= 100) {
                    groupManager.setGroupScore(groupName, score);
                    updateTable.run();
                } else {
                    JOptionPane.showMessageDialog(panel, "分数必须在0-100之间！");
                }
            }
        } catch (NumberFormatException ex) {
            JOptionPane.showMessageDialog(panel, "请输入有效的数字！");
        }
    }

    //学生管理面板
    private static JPanel createStudentPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        String[] columnNames = {"学号", "姓名", "班级", "小组", "成绩"};
        Object[][] data = new Object[0][5];
        //使用 JTable 以表格形式展示学生信息
        JTable table = new JTable(data, columnNames);
        //提供新增学生的按钮，用户需要输入学号、姓名、选择班级和小组，并输入成绩
        JButton addButton = new JButton("新增学生");

        addButton.addActionListener(e -> {
            if (classManager.getAllClasses().isEmpty() || groupManager.getAllGroups().isEmpty()) {
                JOptionPane.showMessageDialog(null, "请先添加班级和小组！");
                return;
            }

            String id = JOptionPane.showInputDialog("请输入学号：");
            String name = JOptionPane.showInputDialog("请输入姓名：");
            String className = (String) JOptionPane.showInputDialog(null,
                    "选择班级", "班级选择",
                    JOptionPane.QUESTION_MESSAGE, null,
                    classManager.getAllClasses().toArray(),
                    classManager.getAllClasses().get(0));
            String groupName = (String) JOptionPane.showInputDialog(null,
                    "选择小组", "小组选择",
                    JOptionPane.QUESTION_MESSAGE, null,
                    groupManager.getAllGroups().toArray(),
                    groupManager.getAllGroups().get(0));

            // 添加成绩输入
            String scoreStr = JOptionPane.showInputDialog("请输入成绩：");
            Double score = null;

            try {
                if (scoreStr != null && !scoreStr.trim().isEmpty()) {
                    score = Double.parseDouble(scoreStr);
                }
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(null, "成绩必须是数字！");
                return;
            }

            if (id != null && name != null && className != null && groupName != null && score != null) {
                studentManager.addStudent(new Student(id, name, className, groupName, score));
                updateStudentTable(table);
            }
        });

        panel.add(new JScrollPane(table), BorderLayout.CENTER);
        panel.add(addButton, BorderLayout.SOUTH);
        return panel;
    }

    //随机点名板块
    private static JPanel createRandomPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        JTextArea resultArea = new JTextArea();
        resultArea.setEditable(false);

        //提供三个按钮，分别以班级、小组或学生为单位随机点名
        JPanel buttonPanel = new JPanel();
        JButton randomClassButton = new JButton("随机班级点名");
        JButton randomGroupButton = new JButton("随机小组点名");
        JButton randomStudentButton = new JButton("随机学生点名");

        // 修改这三个按钮的事件处理器
        randomClassButton.addActionListener(e -> {
            Student student = randomSelector.selectRandomStudent("class", studentManager);
            displayRandomResult(student, resultArea);
        });

        randomGroupButton.addActionListener(e -> {
            Student student = randomSelector.selectRandomStudent("group", studentManager);
            displayRandomResult(student, resultArea);
        });

        randomStudentButton.addActionListener(e -> {
            Student student = randomSelector.selectRandomStudent("student", studentManager);
            displayRandomResult(student, resultArea);
        });

        buttonPanel.add(randomClassButton);
        buttonPanel.add(randomGroupButton);
        buttonPanel.add(randomStudentButton);

        panel.add(new JScrollPane(resultArea), BorderLayout.CENTER);
        panel.add(buttonPanel, BorderLayout.SOUTH);
        return panel;
    }

    // 创建考勤管理面板
    private static JPanel createAttendancePanel() {
        JPanel panel = new JPanel(new BorderLayout());

        // 创建表格显示考勤记录
        String[] columnNames = {"学号", "姓名", "日期", "考勤状态"};
        DefaultTableModel tableModel = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        JTable attendanceTable = new JTable(tableModel);

        // 创建按钮面板
        JPanel buttonPanel = new JPanel();
        JButton addButton = new JButton("记录考勤");
        JButton viewButton = new JButton("查看记录");

        // 记录考勤按钮事件
        addButton.addActionListener(e -> {
            // 获取学生列表
            ArrayList<Student> students = studentManager.getAllStudents();
            if (students.isEmpty()) {
                JOptionPane.showMessageDialog(panel, "请先添加学生！");
                return;
            }

            // 选择学生
            Student student = (Student) JOptionPane.showInputDialog(
                    panel,
                    "选择学生",
                    "考勤记录",
                    JOptionPane.QUESTION_MESSAGE,
                    null,
                    students.toArray(),
                    students.get(0)
            );

            if (student != null) {
                // 选择考勤状态
                String[] statuses = {"出席", "迟到", "请假", "缺席"};
                String status = (String) JOptionPane.showInputDialog(
                        panel,
                        "选择考勤状态",
                        "考勤记录",
                        JOptionPane.QUESTION_MESSAGE,
                        null,
                        statuses,
                        statuses[0]
                );

                if (status != null) {
                    // 记录考勤
                    String date = new java.text.SimpleDateFormat("yyyy-MM-dd")
                            .format(new Date());
                    studentManager.recordAttendance(student.getName(), status, date);

                    // 更新表格
                    tableModel.addRow(new Object[]{
                            student.getId(),
                            student.getName(),
                            date,
                            status
                    });
                }
            }
        });

        // 查看记录按钮事件
        viewButton.addActionListener(e -> {
            String studentName = JOptionPane.showInputDialog("请输入学生姓名：");
            if (studentName != null && !studentName.trim().isEmpty()) {
                // 清空表格
                tableModel.setRowCount(0);
                // 获取并显示记录
                studentManager.getAttendanceRecords(studentName).forEach(record -> {
                    tableModel.addRow(new Object[]{
                            studentManager.getStudentById(record.studentId).getId(),
                            studentName,
                            record.date,
                            record.status
                    });
                });
            }
        });

        buttonPanel.add(addButton);
        buttonPanel.add(viewButton);

        panel.add(new JScrollPane(attendanceTable), BorderLayout.CENTER);
        panel.add(buttonPanel, BorderLayout.SOUTH);

        return panel;
    }

    // 创建答题记录面板
    private static JPanel createAnswerRecordPanel() {
        JPanel panel = new JPanel(new BorderLayout());

        // 创建表格显示答题记录
        String[] columnNames = {"学号", "姓名", "题目编号", "答题结果", "日期"};
        DefaultTableModel tableModel = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        JTable answerTable = new JTable(tableModel);

        // 创建按钮面板
        JPanel buttonPanel = new JPanel();
        JButton addButton = new JButton("记录答题");
        JButton viewButton = new JButton("查看记录");

        // 记录答题按钮事件
        addButton.addActionListener(e -> {
            // 获取学生列表
            ArrayList<Student> students = studentManager.getAllStudents();
            if (students.isEmpty()) {
                JOptionPane.showMessageDialog(panel, "请先添加学生！");
                return;
            }

            // 选择学生
            Student student = (Student) JOptionPane.showInputDialog(
                    panel,
                    "选择学生",
                    "答题记录",
                    JOptionPane.QUESTION_MESSAGE,
                    null,
                    students.toArray(),
                    students.get(0)
            );

            if (student != null) {
                // 输入题目编号
                String questionId = JOptionPane.showInputDialog("请输入题目编号：");
                if (questionId != null && !questionId.trim().isEmpty()) {
                    // 选择答题结果
                    String[] results = {"正确", "错误"};
                    String result = (String) JOptionPane.showInputDialog(
                            panel,
                            "选择答题结果",
                            "答题记录",
                            JOptionPane.QUESTION_MESSAGE,
                            null,
                            results,
                            results[0]
                    );

                    if (result != null) {
                        // 记录答题情况
                        String date = new java.text.SimpleDateFormat("yyyy-MM-dd")
                                .format(new Date());
                        studentManager.recordAnswer(student.getName(), questionId,
                                result.equals("正确"), date);

                        // 更新表格
                        tableModel.addRow(new Object[]{
                                student.getId(),
                                student.getName(),
                                questionId,
                                result,
                                date
                        });
                    }
                }
            }
        });

        // 查看记录按钮事件
        viewButton.addActionListener(e -> {
            String studentName = JOptionPane.showInputDialog("请输入学生姓名：");
            if (studentName != null && !studentName.trim().isEmpty()) {
                // 清空表格
                tableModel.setRowCount(0);
                // 获取并显示记录
                studentManager.getAnswerRecords(studentName).forEach(record -> {
                    tableModel.addRow(new Object[]{
                            studentManager.getStudentById(record.studentId).getId(),
                            studentName,
                            record.questionId,
                            record.correct ? "正确" : "错误",
                            record.date
                    });
                });
            }
        });

        buttonPanel.add(addButton);
        buttonPanel.add(viewButton);

        panel.add(new JScrollPane(answerTable), BorderLayout.CENTER);
        panel.add(buttonPanel, BorderLayout.SOUTH);

        return panel;
    }


    private static void updateList(DefaultListModel<String> model, ArrayList<String> items) {
        model.clear();
        for (String item : items) {
            model.addElement(item);
        }
    }

    private static void updateStudentTable(JTable table) {
        ArrayList<Student> students = studentManager.getAllStudents();
        Object[][] data = new Object[students.size()][5];
        for (int i = 0; i < students.size(); i++) {
            Student s = students.get(i);
            data[i] = new Object[]{s.getId(), s.getName(), s.getClassName(), s.getGroupName(), s.getScore()};
        }
        table.setModel(new DefaultTableModel(
                data,
                new String[]{"学号", "姓名", "班级", "小组", "成绩"}
        ));
    }

    private static void displayRandomResult(Student student, JTextArea resultArea) {
        if (student == null) {
            resultArea.setText("没有可选择的学生！");
            return;
        }
        resultArea.setText(String.format(
                "选中的学生：\n学号：%s\n姓名：%s\n班级：%s\n小组：%s\n成绩：%.1f",
                student.getId(), student.getName(),
                student.getClassName(), student.getGroupName(),
                student.getScore()
        ));
    }


}